package com.sihan.framework.etm.common.util;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.framework.exception.BusinessException;
import com.sihan.framework.etm.entity.MailAndSmsLog;
import com.sihan.framework.etm.mapper.MailAndSmsLogMapper;

@Service
public class AliSMSSendImpl implements ISMSTempSendable {

	@Autowired
	private SMSConfig smsConfig;
	
	@Autowired
	private MailAndSmsLogMapper mailAndSmsLogMapper;

	private static IAcsClient client;
	
	private static final ExecutorService executorService = Executors.newCachedThreadPool();

	//产品名称:云通信短信API产品,开发者无需替换
	static final String product = "Dysmsapi";

	//产品域名,开发者无需替换
	static final String domain = "dysmsapi.aliyuncs.com";

	/**
	 * @throws Exception
	 * @return void
	 * @author 张荣英
	 * @date Aug 5, 2019 5:45:30 PM
	 */
	private void initClient() throws Exception {
		if (null == client) {
			IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", smsConfig.getAccessKeyId(), smsConfig.getSecret());
			DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
			client = new DefaultAcsClient(profile);
		}
	}

	/**
	 * 构建Request
	 * @param phones
	 * @param templateCode
	 * @param paramMap
	 * @return
	 * @throws Exception
	 * @return SendSmsRequest
	 * @author 张荣英
	 * @date Aug 5, 2019 5:46:08 PM
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public SendSmsRequest buildRequest(String phones, String templateCode, Map<String, Object> paramMap) throws Exception {
		
		if(phones != null ){
			phones = phones.trim();
		}

		StringBuilder sb = new StringBuilder();
		sb.append("{");
		Iterator typeIterator = paramMap.entrySet().iterator();

		// 发送消息
		while (typeIterator.hasNext()) {
			Map.Entry<String, Object> entry = (Map.Entry<String, Object>) typeIterator.next();
			String name = entry.getKey();
			sb.append(name);
			sb.append(":'");
			String value = entry.getValue() == null ? "" : entry.getValue().toString();
			sb.append(value);
			sb.append("',");
		}
		String params = sb.toString();
		if (params.length() > 1) {
			params = params.substring(0, params.length() - 1);
		}
		params += "}";
		SendSmsRequest request = new SendSmsRequest();
		request.setSignName(smsConfig.getSignName());
		//request.setSignName("慧停");
		request.setTemplateCode(templateCode);
		request.setTemplateParam(params);
		request.setPhoneNumbers(phones);
		return request;
	}

	/**
	 * 同步发送单个消息
	 */
	@Override
	public void sendSmsSync(String phone, String templateCode, Map<String, Object> paramMap) {
		try {
			initClient();
			SendSmsRequest request = buildRequest(phone, templateCode, paramMap);
			if (smsConfig.getSendable()) {
				client.getAcsResponse(request);
				MailAndSmsLog log = setModelAttribute(request.getPhoneNumbers(), request.getTemplateCode() , request.getTemplateParam());
				mailAndSmsLogMapper.insert(log);
			}
		} catch (Exception e) {
			throw new BusinessException("短信发送错误",e);
		}
	}

	/**
	 * 同步发送多个消息
	 */
	@Override
	public void sendSmsSync(List<String> phoneList, String templateCode, Map<String, Object> paramMap) {
		try {
			initClient();
			String phones = contactPhoneStr(phoneList);
			SendSmsRequest request = buildRequest(phones, templateCode, paramMap);

			if (smsConfig.getSendable()) {
				client.getAcsResponse(request);
				
				MailAndSmsLog log = setModelAttribute(request.getPhoneNumbers(), request.getTemplateCode() , request.getTemplateParam());
				mailAndSmsLogMapper.insert(log);
			}
		} catch (Exception e) {
			throw new BusinessException("短信发送错误",e);
		}
	}

	/**
	 * 异步发送单个消息
	 */
	@Override
	public void sendSmsAsync(String phone, String templateCode, Map<String, Object> paramMap) {
		List<String> toPhones = new ArrayList<String>();
		toPhones.add(phone);
		sendSmsAsync(toPhones, templateCode, paramMap);
	}

	/**
	 * 异步发送多个消息
	 */
	@Override
	public void sendSmsAsync(List<String> toPhoneNumbers, String templateCode, Map<String, Object> paramMap) {
		if (null != toPhoneNumbers && toPhoneNumbers.size() != 0) {
			SendSmsRequest request = null;
			try {
				initClient();
				String phones = contactPhoneStr(toPhoneNumbers);
				request = buildRequest(phones, templateCode, paramMap);
			} catch (Exception e) {
				throw new BusinessException("短信发送错误",e);
			}

			if (smsConfig.getSendable()) {
				executorService.execute(
						new AliSMSSendTask(client, request, smsConfig.getResendTimes(), smsConfig.getResendInterval(), mailAndSmsLogMapper));
			}
		}
	}

	/**
	 * 拼接手机号码为字符串
	 * @param phoneList
	 * @return
	 * @return String
	 * @author 张荣英
	 * @date Aug 5, 2019 5:47:24 PM
	 */
	private String contactPhoneStr(List<String> phoneList) {
		StringBuffer phoneStr = new StringBuffer();
		for (String phone : phoneList) {
			phoneStr.append(phone).append(",");
		}
		return phoneStr.toString().substring(0, phoneStr.toString().length() - 1);
	}

	private MailAndSmsLog setModelAttribute(String phones,String templateCode , String content){
		MailAndSmsLog log = new MailAndSmsLog();
		log.setPhoneOrMail(phones);
		log.setSubject(templateCode);
		log.setContent(content);
		log.setSendDate(new Date());
		log.setType((short) 1);
		log.setIsSuccess((short) 1);
		return log;
	}

}
